package light.mvc.service.wxn.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import light.mvc.dao.BaseDaoI;
import light.mvc.model.wxn.AccessTokenBO;
import light.mvc.pageModel.base.Json;
import light.mvc.pageModel.base.PageFilter;
import light.mvc.pageModel.wxn.AccessTokenVO;
import light.mvc.pageModel.wxn.AnalysisUserVO;
import light.mvc.pageModel.wxn.CumulateUserVO;
import light.mvc.service.wxn.AccessTokenServiceI;
import light.mvc.service.wxn.AnalysisUserServiceI;
import light.mvc.service.wxn.CumulateUserServiceI;
import light.mvc.service.wxn.WeiMenuServiceI;
import light.mvc.utils.BasisHttpRequest;
import light.mvc.utils.SysLogger;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AccessTokenServiceImpl implements AccessTokenServiceI {

	// 菜单创建（POST） 限100（次/天）
	public static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	public static String send_message_url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN";
	public static String qrcode_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
	public static String user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	public static String menu_delete_url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	public static String datacube_getusersummarye_url="https://api.weixin.qq.com/datacube/getusersummary?access_token=ACCESS_TOKEN";
	public static String datacube_getusercumulate_url="https://api.weixin.qq.com/datacube/getusercumulate?access_token=ACCESS_TOKEN";
	//获取分组
	public static String tags_get_url="https://api.weixin.qq.com/cgi-bin/tags/get?access_token=ACCESS_TOKEN";
	public static String tags_create_url="https://api.weixin.qq.com/cgi-bin/tags/create?access_token=ACCESS_TOKEN";
	public static String tags_delete_url="https://api.weixin.qq.com/cgi-bin/tags/delete?access_token=ACCESS_TOKEN";
	public static String user_tagGet_url="https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=ACCESS_TOKEN";
	
	@Autowired
	private BaseDaoI<AccessTokenBO> accessTokenDao;
	
	@Autowired
	private WeiMenuServiceI weiMenuService;
	
	@Autowired
	private AnalysisUserServiceI analysisUserService;

	@Autowired
	private CumulateUserServiceI cumulateUserService;
	
	@Override
	public void add(AccessTokenVO r) {
		AccessTokenBO t = new AccessTokenBO();
		t.setAppid(r.getAppid());
		t.setAccess_Token(r.getAccess_Token());
		t.setExpires_in(r.getExpires_in());
		t.setExpiresTime(new Date());
		t.setSecret(r.getSecret());
		t.setWeiId(r.getWeiId());
		t.setWeiName(r.getWeiName());
		accessTokenDao.save(t);
	}

	@Override
	public void delete(Long id) {
		AccessTokenBO t = accessTokenDao.get(AccessTokenBO.class, id);
		accessTokenDao.delete(t);
	}

	@Override
	public void edit(AccessTokenVO r) {
		AccessTokenBO t = accessTokenDao.get(AccessTokenBO.class, r.getId());
		t.setAppid(r.getAppid());
		t.setAccess_Token(r.getAccess_Token());
		t.setExpires_in(r.getExpires_in());
		t.setExpiresTime(new Date());
		t.setSecret(r.getSecret());
		t.setWeiId(r.getWeiId());
		t.setWeiName(r.getWeiName());
		accessTokenDao.update(t);
	}
	
	@Override
	public AccessTokenVO get(Long id) {
		AccessTokenBO t = accessTokenDao.get(AccessTokenBO.class, id);
		AccessTokenVO r = new AccessTokenVO();
		r.setId(t.getId());
		r.setAppid(t.getAppid());
		r.setAccess_Token(t.getAccess_Token());
		r.setExpires_in(t.getExpires_in());
		r.setExpiresTime(t.getExpiresTime());
		r.setSecret(t.getSecret());
		r.setWeiId(t.getWeiId());
		r.setWeiName(t.getWeiName());
		return r;
	}

	@Override
	public List<AccessTokenVO> dataGrid(AccessTokenVO accessToken, PageFilter ph) {
		List<AccessTokenVO> ul = new ArrayList<AccessTokenVO>();
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from AccessTokenBO t ";
		List<AccessTokenBO> l = accessTokenDao.find(
				hql + whereHql(accessToken, params) + orderHql(ph), params,
				ph.getPage(), ph.getRows());
		for (AccessTokenBO t : l) {
			AccessTokenVO u = new AccessTokenVO();

			BeanUtils.copyProperties(t, u);
			ul.add(u);
		}
		return ul;
	}

	@Override
	public Long count(AccessTokenVO accessToken, PageFilter ph) {
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from AccessTokenBO t ";
		return accessTokenDao.count(
				"select count(*) " + hql + whereHql(accessToken, params),
				params);
	}

	private String whereHql(AccessTokenVO accessToken,
			Map<String, Object> params) {
		String hql = "";
		if (accessToken != null) {
			hql += " where 1=1 ";
			if (accessToken.getAppid() != null) {
				hql += " and t.name like :name";
				params.put("name", "%%" + accessToken.getAppid() + "%%");
			}
		}
		return hql;
	}

	private String orderHql(PageFilter ph) {
		String orderString = "";
		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
	
	public void scanFindByAppid() {
		List<AccessTokenBO> listAccessTokenBO=accessTokenDao.find("from AccessTokenBO");
		AccessTokenVO accessTokenVO=new AccessTokenVO();
		for(AccessTokenBO accessTokenBO:listAccessTokenBO){
			accessTokenVO=new AccessTokenVO();
			BeanUtils.copyProperties(accessTokenBO, accessTokenVO);
			long time = System.currentTimeMillis() - accessTokenVO.getExpiresTime().getTime();		
			if (time > accessTokenVO.getExpires_in()*1000 || accessTokenVO.getAccess_Token()=="") {
				String url=token_url.replace("APPID", accessTokenVO.getAppid()).replace("APPSECRET", accessTokenVO.getSecret());
				BasisHttpRequest httpRequest = new BasisHttpRequest();
				JSONObject jsonObject = BasisHttpRequest.httpRequest(url, "POST", "");
				// 如果请求成功
				if (null != jsonObject) {
					try {
						accessTokenVO.setExpires_in(jsonObject.getInt("expires_in"));
						accessTokenVO.setAccess_Token(jsonObject.getString("access_token"));
						edit(accessTokenVO);
					} catch (JSONException e) {
						SysLogger.error(this.getClass(),"获取token失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode")
								+ jsonObject.getString("errmsg"));
					}
				}
			}
		}
	}
	
	public AccessTokenVO appidToAccessToken(String appid) {
		List<AccessTokenBO> listAccessTokenBO=accessTokenDao.find("from AccessTokenBO where appid='"+appid+"'");
		AccessTokenVO accessTokenVO=new AccessTokenVO();
		for(AccessTokenBO accessTokenBO:listAccessTokenBO){
			accessTokenVO=new AccessTokenVO();
			BeanUtils.copyProperties(accessTokenBO, accessTokenVO);
			long time = System.currentTimeMillis() - accessTokenVO.getExpiresTime().getTime();		
			if (time > accessTokenVO.getExpires_in()*1000 || accessTokenVO.getAccess_Token()=="") {
				String url=token_url.replace("APPID", accessTokenVO.getAppid()).replace("APPSECRET", accessTokenVO.getSecret());
				BasisHttpRequest httpRequest = new BasisHttpRequest();
				JSONObject jsonObject = BasisHttpRequest.httpRequest(url, "POST", "");
				// 如果请求成功
				if (null != jsonObject) {
					try {
						accessTokenVO.setExpires_in(jsonObject.getInt("expires_in"));
						accessTokenVO.setAccess_Token(jsonObject.getString("access_token"));
						edit(accessTokenVO);
					} catch (JSONException e) {
						SysLogger.error(this.getClass(),"获取token失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode")
								+ jsonObject.getString("errmsg"));
					}
				}
			}
		}
		return accessTokenVO;
	}
	
	public Boolean menuCrate(String appid){
		AccessTokenVO accessTokenVO=appidToAccessToken(appid);
		if(accessTokenVO.getAccess_Token()==null){
			return false;
		}
		String url=menu_create_url.replace("ACCESS_TOKEN", accessTokenVO.getAccess_Token());
		BasisHttpRequest httpRequest = new BasisHttpRequest();
		
		JSONObject obj= weiMenuService.treeMenu();
		
		String menu=obj.toString();

		JSONObject jsonObject = httpRequest.httpRequest(url,"POST", menu);
		if (null != jsonObject) {
			try {
				if(jsonObject.getInt("errcode")==0){
					return true;
				}else{
					return false;
				}
			} catch (JSONException e) {
				SysLogger.error(this.getClass(),"异常code："+jsonObject.getString("errcode")+" 异常消息:"+jsonObject.getString("errmsg"));
			}
		}
		return false;
	}
	
	public Boolean menuDelete(String appid){
		AccessTokenVO accessTokenVO=appidToAccessToken(appid);
		if(accessTokenVO.getAccess_Token()==null){
			return false;
		}
		String url=menu_delete_url.replace("ACCESS_TOKEN", accessTokenVO.getAccess_Token());
		BasisHttpRequest httpRequest = new BasisHttpRequest();
		JSONObject jsonObject = httpRequest.httpRequests(url);
		//JSONObject postData = JSONObject.fromObject(obj);
		
		if (null != jsonObject) {
			try {
				if(jsonObject.getInt("errcode")==0){
					return true;
				}else{
					return false;
				}
			} catch (JSONException e) {
				SysLogger.error(this.getClass(),"删除异常code："+jsonObject.getString("errcode")+" 异常消息:"+jsonObject.getString("errmsg"));
			}
		}
		return false;
	}
	
	public Json addAnalysisUser(String appid){
		Json j = new Json();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //过去1天
        c.setTime(new Date());
        c.add(Calendar.DATE, - 1);
        Date d1 = c.getTime();
        String today = format.format(d1);
        JSONObject lastDate = new JSONObject();
        lastDate.accumulate("end_date",today);
		lastDate.accumulate("begin_date", today);
		
		JSONObject nowDate = new JSONObject();
		nowDate.accumulate("end_date",today);
		nowDate.accumulate("begin_date", today);
		
		java.util.Date date1;
		try {
			date1 = format.parse(today);
		} catch (ParseException e1) {
			date1=new Date();
		}  
		
		AnalysisUserVO analysisUserVO=new AnalysisUserVO();		
		analysisUserVO.setRefDate(date1);	
		if(!(analysisUserService.isThere(analysisUserVO))){
			AccessTokenVO accessTokenVO=appidToAccessToken(appid);
			if(accessTokenVO.getAccess_Token()==null){
				j.setSuccess(false);
				j.setMsg("appid有误！");
				return j;
			}
			String weiAppid=accessTokenVO.getAppid();
			String weiName=accessTokenVO.getWeiName();

			String user_url=datacube_getusersummarye_url.replace("ACCESS_TOKEN", accessTokenVO.getAccess_Token());
			BasisHttpRequest httpRequest = new BasisHttpRequest();
			JSONObject userJsonObject = httpRequest.httpRequest(user_url,"POST", lastDate.toString());
			try {
				if (null != userJsonObject) {
							
					if(userJsonObject.getString("list") != null){
						//存
						JSONArray userJSONArray=userJsonObject.getJSONArray("list");
						int userLength=userJSONArray.length();
						for (int i = 0; i < userLength; i++) {
							analysisUserVO=new AnalysisUserVO();
							analysisUserVO.setAppid(weiAppid);
							analysisUserVO.setWeiName(weiName);
							analysisUserVO.setRefDate(date1);
							analysisUserVO.setCancelUser(userJSONArray.getJSONObject(i).getInt("cancel_user"));
							analysisUserVO.setNewUser(userJSONArray.getJSONObject(i).getInt("new_user"));
							analysisUserVO.setUserSource(userJSONArray.getJSONObject(i).getInt("user_source"));
							analysisUserService.add(analysisUserVO);
						}
						j.setSuccess(true);
						j.setMsg("操作成功！");
					}else{
						j.setSuccess(false);
						j.setMsg(userJsonObject.toString());
					}
				}
			} catch (JSONException e) {
				SysLogger.error(this.getClass(),"异常："+userJsonObject.toString());
			}
		}else{
			j.setSuccess(true);
			j.setMsg("已经同步过了！");
		}
		return j;
	}
	
	public Json addCumulateUser(String appid){
		Json j = new Json();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //过去1天
        c.setTime(new Date());
        c.add(Calendar.DATE, - 1);
        Date d1 = c.getTime();
        String today = format.format(d1);
        JSONObject lastDate = new JSONObject();
        lastDate.accumulate("end_date",today);
		lastDate.accumulate("begin_date", today);
		
		JSONObject nowDate = new JSONObject();
		nowDate.accumulate("end_date",today);
		nowDate.accumulate("begin_date", today);
		
		java.util.Date date1;
		try {
			date1 = format.parse(today);
		} catch (ParseException e1) {
			date1=new Date();
		} 
		
		CumulateUserVO cumulateUserVO=new CumulateUserVO();
		cumulateUserVO.setRefDate(date1);
		if(!(cumulateUserService.isThere(cumulateUserVO))){
			AccessTokenVO accessTokenVO=appidToAccessToken(appid);
			if(accessTokenVO.getAccess_Token()==null){
				j.setSuccess(false);
				j.setMsg("appid有误！");
				return j;
			}
			cumulateUserVO.setAppid(accessTokenVO.getAppid());
			cumulateUserVO.setWeiName(accessTokenVO.getWeiName());
			String count_url=datacube_getusercumulate_url.replace("ACCESS_TOKEN", accessTokenVO.getAccess_Token());
			BasisHttpRequest httpRequest = new BasisHttpRequest();
			JSONObject countJsonObject = httpRequest.httpRequest(count_url,"POST", nowDate.toString());
			try {
				if ( null != countJsonObject) {		
					if(countJsonObject.getString("list") != null){
						//存
						cumulateUserVO.setCumulateUser(countJsonObject.getJSONArray("list").getJSONObject(0).getInt("cumulate_user"));
						cumulateUserService.add(cumulateUserVO);
						j.setSuccess(true);
						j.setMsg("操作成功！");
					}else{
						j.setSuccess(false);
						j.setMsg(j.getMsg()+countJsonObject.toString());
					}
				}
			} catch (JSONException e) {
				SysLogger.error(this.getClass(),"异常："+ countJsonObject.toString());
			}
		}else{
			j.setSuccess(true);
			j.setMsg("已经同步过了");
		}
		
		return j;
	}
	
	
	public Json tagsGet(String appid){
		Json j=new Json();
		AccessTokenVO accessTokenVO=appidToAccessToken(appid);
		if(accessTokenVO.getAccess_Token()==null){
			j.setSuccess(false);
			j.setMsg("appid有误！");
			return j;
		}
		String tagsGet_url=tags_get_url.replace("ACCESS_TOKEN", accessTokenVO.getAccess_Token());
		BasisHttpRequest httpRequest = new BasisHttpRequest();
		JSONObject tagsGetJsonObject = httpRequest.httpRequest(tagsGet_url,"POST","");
		System.out.println("tagsGetJsonObject:"+tagsGetJsonObject);
		//{"tags":[{"id":2,"count":1,"name":"星标组"},{"id":133,"count":1,"name":"上海龙之梦"}]}
		
		try {
			if ( null != tagsGetJsonObject) {		
				if(tagsGetJsonObject.getString("tags") != null){
					//存
					
					j.setSuccess(true);
					j.setMsg("操作成功！");
				}else{
					j.setSuccess(false);
					j.setMsg(j.getMsg()+tagsGetJsonObject.toString());
				}
			}
		} catch (JSONException e) {
			SysLogger.error(this.getClass(),"异常："+ tagsGetJsonObject.toString());
		}
		
		return j;
	}

}